# coding: utf-8

import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')

class Query(db.Model):
    isbn = db.StringProperty()
    timestamp = db.DateTimeProperty(auto_now_add=True)
    user = db.UserProperty()

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            logout_url = users.create_logout_url('/')
        else:
            login_url = users.create_login_url(self.request.uri)    
        html = os.path.join(TEMPLATE_DIR, 'index.django.html')
        self.response.out.write(template.render(html, locals()))
        
class IsbnFetch(webapp.RequestHandler):
    def get(self):
        self.redirect('/')
    def post(self):
        for isbn in self.request.get('isbns', '').split():
            query = Query(isbn=isbn, user=users.get_current_user())
            query.put()
        queries = Query.all()
        if users.is_current_user_admin():
            admin = True
        else: # restrict results to queries by the current user
            queries.filter("user =", users.get_current_user())
        queries.order("-timestamp")
        html = os.path.join(TEMPLATE_DIR, 'queue.django.html')
        self.response.out.write(template.render(html, locals()))

application = webapp.WSGIApplication([
                                        ('/', MainPage),
                                        ('/isbn', IsbnFetch),
                                     ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
